package com.test.controllers;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class FileDownloadController {

    // 定义文件存储的基础目录，根据实际情况修改
    private static final String FILE_DIRECTORY = "C:\\Users\\42078\\Desktop\\tmp";

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String fileName) {
        try {
            // 安全解析文件路径，防止路径遍历攻击
            Path filePath = Paths.get(FILE_DIRECTORY).resolve(fileName).normalize();
            if (!filePath.startsWith(FILE_DIRECTORY)) {
                return ResponseEntity.badRequest().body(null);
            }

            // 加载文件资源
            Resource resource = new UrlResource(filePath.toUri());

            // 检查文件是否存在且可读
            if (resource.exists() && resource.isReadable()) {
                // 设置响应头
                String contentType = "application/octet-stream";
                String headerValue = "attachment; filename=\"" + resource.getFilename() + "\"";

                return ResponseEntity.ok()
                        .contentType(MediaType.parseMediaType(contentType))
                        .header(HttpHeaders.CONTENT_DISPOSITION, headerValue)
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.badRequest().body(null);
        }
    }
}